package com.web.utils;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.reflection.ArrayUtil;

import java.util.Random;

public class InviteCode {

    /**
     * 生成数字加字母N位随机数
     * @param n 长度
     * @return
     */
    private static String getItemID( int n )
    {
        String val = "";
        Random random = new Random();
        for ( int i = 0; i < n; i++ )
        {
            String str = random.nextInt( 2 ) % 2 == 0 ? "num" : "char";
            if ( "char".equalsIgnoreCase( str ) )
            { // 产生字母
                int nextInt = random.nextInt( 2 ) % 2 == 0 ? 65 : 97;
                // System.out.println(nextInt + "!!!!"); 1,0,1,1,1,0,0
                val += (char) ( nextInt + random.nextInt( 26 ) );
            }
            else if ( "num".equalsIgnoreCase( str ) )
            { // 产生数字
                val += String.valueOf( random.nextInt( 10 ) );
            }
        }
        return val;
    }

    /**
     * 生成邀请码
     * @param lengths 邀请码长度
     * @param inviteCode 上线邀请码
     * @param level 分销等级
     * @return
     */
    public static String getInviteCodeLevel(int lengths,String inviteCode,Integer level){
        String[] s = inviteCode.split("-");
        if (s.length == level){
            s = ArrayUtils.remove(s,0);
            return StringUtils.join(s,"-") +"-"+ getItemID(lengths).toUpperCase();
        }else{
            return inviteCode + "-" + getItemID(lengths).toUpperCase();
        }
    }

    /**
     * 无上线生成邀请码
     * @param lengths 邀请码长度
     * @return
     */
    public static String getInviteCode(int lengths){
        return getItemID(lengths).toUpperCase();
    }
}
